﻿using Iot.Device.Sht3x;

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Device.Gpio;
using System.Device.I2c;
using System.Text;
using System.Threading;
using System.Linq;
using System.IO.Ports;
using IotDeviceToolHepler.WiringOPSharp;
using IotDeviceToolHepler.Utils;

namespace IotDeviceToolHepler.Device
{

    /// <summary>
    /// 串口调用示例
    /// </summary>
    public static class DeviceSerial
    {
        //运行调用例子
        public static void Test()
        {
            while (true)
            {
                GetDataAndWriteByte();
            }
        }

        /// <summary>
        /// 串口调用,发送字节组
        /// </summary>
        public static void GetDataAndWriteByte()
        {
            string portName = "/dev/ttyS3";
            int baudRate = 9600;
            //portName树莓派调用/dev/ttyAMA0
            //portName香橙派调用/dev/ttyS3
            SerialPort serial = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One);
            serial.Open();
            // DataReceived是串口类的一个事件，通过+=运算符订阅事件，如果串口接收到数据就触发事件，调用DataReceive_Method事件处理方法
            serial.DataReceived += new SerialDataReceivedEventHandler(GetDataAndWriteByteDataReceiveMethod);
            while (true)
            {
                //查光照度指令
                serial.Write(DataTypeChangeHelper.StrToHexByte("01 03 00 02 00 02 65 CB"), 0, 8);
                Thread.Sleep(2000);
            }
        }

        /// <summary>
        /// getDataAndWriteByte接收信息事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void GetDataAndWriteByteDataReceiveMethod(object sender, SerialDataReceivedEventArgs e)
        {
            //sender是事件触发对象，通过它可以获取到mySerialPort
            SerialPort serialport = (SerialPort)sender;
            int len = serialport.BytesToRead;
            byte[] recvdata = new byte[len];
            serialport.Read(recvdata, 0, len);
            var str = DataTypeChangeHelper.byteToHexStr(recvdata);
            if (str.Length > 10)
            {
                string result = str.Substring(6, 8);
                int result16 = DataTypeChangeHelper.To16Convert10(result);
                Console.WriteLine("");
                Console.WriteLine(DateTime.Now + " 光照强度:" + (result16 / 1000.0).ToString() + "lur");
            }
        }




        /// <summary>
        /// 串口调用,发送char
        /// </summary>
        public static void GetDataAndWriteChar()
        {
            var port = new SerialPort("/dev/ttyS0");
            port.BaudRate = 115200;
            port.DataBits = 8;
            port.Parity = Parity.None;
            port.StopBits = StopBits.One;
            port.Open();
            if (port.IsOpen)
            {
                Console.WriteLine("Serial Is Open");
                char[] cs = new char[] { 'c', 'x', 'd' };
                port.Write(cs, 0, cs.Length);
                Console.WriteLine("Serial Is Close");
                port.DataReceived += GetDataAndWriteCharPortDataReceived;
            }
        }
        private static void GetDataAndWriteCharPortDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            var s = sender as SerialPort;
            int len = s.ReadByte();
            var chars = new byte[len];
            s.Read(chars, 0, len);
            var str = Encoding.Default.GetString(chars);
            Console.WriteLine(str);
        }

        /// <summary>
        /// 通过WiringOP 操作串口
        /// </summary>
        public static void GetDataAndWriteStringbyWiringOP()
        {
            string device = "/dev/ttyS3";
            if (Setup.WiringPiPiSetup() < 0)
            {
                Console.WriteLine("Wringpi setup failed.");
                return;
            }

            int fd = Serial.SerialOpen(device, 115200);
            if (fd < 0)
            {
                Console.WriteLine("Serial ppen failed.");
                return;
            }
            //异步执行串口读取  
            Task readTask = Task.Run(() => GetDataAndWriteStringbyWiringOpDataReceived(fd));
            //发送
            while (true)
            {
                Console.Write("TX:");
                string send = Console.ReadLine();
                if (string.IsNullOrEmpty(send))
                {
                    continue;
                }
                if (send == "exit")
                {
                    break;
                }
                Serial.SerialPuts(fd, send);
            }
            Serial.SerialClose(fd);
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey(false);
        }

        public static void GetDataAndWriteStringbyWiringOpDataReceived(int fd)
        {
            while (true)
            {
                StringBuilder sb = null;
                while (Serial.SerialDataAvail(fd) > 0)
                {
                    int read = Serial.SerialGetchar(fd);
                    if (read < 0)
                    {
                        Serial.SerialFlush(fd);
                        break;
                    }
                    else
                    {
                        //Remove \r or \n
                        if (read == 10 || read == 13)
                        {
                            continue;
                        }
                        else
                        {
                            if (sb == null)
                            {
                                sb = new StringBuilder();
                            }
                            sb.Append((char)read);
                        }
                    }
                }
                if (sb != null)
                {
                    string readStr = sb.ToString();
                    if (!string.IsNullOrWhiteSpace(readStr))
                    {
                        Console.WriteLine($"RX:{sb.ToString()}");
                    }
                }
            }
        }
    }
}


